package com.beyondsoft.sabg.edu.configure.sercurity;

import com.beyondsoft.sabg.edu.model.db.core.UserAccount;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 自动注入创建者
 */
public class SecurityAuditorAware implements AuditorAware<String> {

	@Override
	public Optional<String> getCurrentAuditor() {

		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if (authentication == null || !authentication.isAuthenticated()) {
			return Optional.empty();
		}
		Object o = authentication.getPrincipal();
		if (o instanceof UserAccount) {
			return Optional.of(((UserAccount) authentication.getPrincipal()).getName());

		} else {
			return Optional.empty();

		}
	}
}